import {
    FooterToolbar,
    PageContainer,
    ProForm,
    ProFormSelect,
    ProFormText,
    ProFormDigit, ProFormRadio, ProFormDateTimePicker, ProColumns, ProTable, ActionType, ProFormInstance,
} from '@ant-design/pro-components';
import {Card, Col, message, Popover, Row, Select, FormInstance, Space, Badge, Button,Form} from 'antd';
import type {FC} from 'react';
import React, {useEffect, useRef, useState} from 'react';
import {hostComputerSelectList, organizationOrderAdd} from './service';
import useStyles from './style.style';
import {dataCenterSelectList} from "@/pages/power/data-center-list/service";
import {Link, useParams, useNavigate} from 'react-router-dom';
import {OrganizationListItem} from "@/pages/organization/org-list/data";
import {organizationDetail} from "@/pages/organization/org-list/service";
import {skuSelectList} from "@/pages/power/sku/sku-list/service";
import {HostComputerListItem} from "@/pages/power/host-computer/list/data";
import {CloseCircleOutlined, PlusOutlined} from "@ant-design/icons";
type InternalNamePath = (string | number)[];
import {useForm} from 'antd/lib/form/Form';
const fieldLabels = {
    organizationId: '租户ID',
    organizationName: '租户名称',
    contactName: '联系人',
    contactPhone: '联系电话',
    address: '公司地址',
    dataCenterId: '资源池',
    skuId: '规格',
};

interface ErrorField {
    name: InternalNamePath;
    errors: string[];
}


const OrganizationOrderAddForm: FC<Record<string, any>> = () => {
    const navigate = useNavigate();
    const params: Record<string, any> = useParams();
    const {styles} = useStyles();
    const [selectedRowsState, setSelectedRows] = useState<HostComputerListItem[]>([]);
    const actionRef = useRef<ActionType>();
    const [messageApi, contextHolder] = message.useMessage();
    const [form] = Form.useForm();

    const onFinish = async (values: Record<string, any>) => {
        setError([]);
        // const selectHostComputerId = selectedRowsState[0]?.hostComputerId | ''
        if (!selectedRowsState || selectedRowsState.length == 0) {
            // message.error("请选择主机！")
            messageApi.open({
                type: 'error',
                content: '请选择主机！',
                className: 'custom-class',
                style: {
                    marginTop: '20vh',
                    // width: '300px',
                    // height:'50px',
                },
            });
            return false
        }
        values["selectHostComputerId"] = selectedRowsState[0]?.hostComputerId;
        try {
            await organizationOrderAdd(values);
            message.success('提交成功');
            navigate('/organization/resource-manager/'+params?.id);
        } catch {
            // console.log
        }
    };
    const [organizationInfo, setOrganizationInfo] = useState<OrganizationListItem>();
    const [loading, setLoading] = useState(true);
    const formRef = useRef<ProFormInstance>();
    const handleSelectChange = () => {
        actionRef.current?.clearSelected();
        actionRef.current?.reload();
    };

    useEffect(() => {
        const fetchOrganizatinData = async () => {
            try {
                const response = await organizationDetail({organizationId: params?.id});
                setOrganizationInfo(response.data);
            } catch (error) {
                console.error('Error fetching form data:', error);
            } finally {
                setLoading(false);
            }
        };
        fetchOrganizatinData();
    }, [params?.id]);
    const [error, setError] = useState<ErrorField[]>([]);
    const getErrorInfo = (errors: ErrorField[]) => {
        const errorCount = errors.filter((item) => item.errors.length > 0).length;
        if (!errors || errorCount === 0) {
            return null;
        }
        const scrollToField = (fieldKey: string) => {
            const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
            if (labelNode) {
                labelNode.scrollIntoView(true);
            }
        };
        const errorList = errors.map((err) => {
            if (!err || err.errors.length === 0) {
                return null;
            }
            const key = err.name[0] as 'name' | 'url' | 'owner' | 'approver' | 'dateRange' | 'type';
            return (
                <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
                    <CloseCircleOutlined className={styles.errorIcon}/>
                    <div className={styles.errorMessage}>{err.errors[0]}</div>
                    <div className={styles.errorField}>{fieldLabels[key]}</div>
                </li>
            );
        });
        return (
            <span className={styles.errorIcon}>
        <Popover
            title="表单校验信息"
            content={errorList}
            overlayClassName={styles.errorPopover}
            trigger="click"
            getPopupContainer={(trigger: HTMLElement) => {
                if (trigger && trigger.parentNode) {
                    return trigger.parentNode as HTMLElement;
                }
                return trigger;
            }}
        >
          <CloseCircleOutlined/>
        </Popover>
                {errorCount}
      </span>
        );
    };
    const onFinishFailed = (errorInfo: any) => {
        setError(errorInfo.errorFields);
    };

    const columns: ProColumns<HostComputerListItem>[] = [
        {
            title: '资源池',
            dataIndex: "dataCenterId",
            valueType: 'select',
            search: true,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await dataCenterSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.name,
                        value: item.dataCenterId,
                    })) || []
                );
            },
        },
        {
            title: '规格',
            dataIndex: "skuId",
            valueType: 'select',
            search: true,
            hidden: true, // 关闭自动换行
            request: async () => {
                const result = await skuSelectList({});
                return (
                    result.data?.map((item) => ({
                        label: item.skuName,
                        value: item.skuId,
                    })) || []
                );
            },
        },
        {
            title: '所属资源池',
            dataIndex: 'dataCenterName',
            valueType: 'text',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '规格',
            dataIndex: 'skuName',
            search: false,
            valueType: 'text',
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '主机ID',
            dataIndex: 'hostComputerId',
            search: false,
            hidden: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '主机名称',
            dataIndex: 'hostComputerName',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '机房编号',
            dataIndex: 'machineRoomNo',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '机柜编号',
            dataIndex: 'cabinetNo',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: 'U位区间',
            dataIndex: 'uPosition',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '主机IP',
            dataIndex: 'hostIp',
            search: true,
            ellipsis: true, // 关闭自动换行
        },
        {
            title: '系统',
            dataIndex: 'systemOS',
            search: false,
            ellipsis: true, // 关闭自动换行
        },
    ];

    return (
        <div>
            {contextHolder}
            {loading ? (
                <div>Loading...</div>
            ) : (
                <ProForm
                    // layout="vertical"
                    layout="horizontal"
                    submitter={{
                        render: (props, dom) => {
                            return (
                                <FooterToolbar>
                                    {getErrorInfo(error)}
                                    {dom}
                                </FooterToolbar>
                            );
                        },
                    }}
                    initialValues={{
                        billingCycle: 'hour',
                        organizationId: organizationInfo?.organizationId,
                        organizationName: organizationInfo?.name,
                        contactName: organizationInfo?.contactName,
                        contactPhone: organizationInfo?.contactPhone,
                        address: organizationInfo?.address,
                        resourceType: "host_computer",
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    formRef={formRef}
                    form={form}
                >
                    <PageContainer>
                        <Card title="租户信息" className={styles.card} bordered={false}>
                            <ProFormText
                                label={fieldLabels.organizationId}
                                name="organizationId"
                                readonly={true}
                                hidden={true}
                            />
                            <ProFormText
                                label="资源类型"
                                name="resourceType"
                                hidden={true}
                            />
                            <Row>
                                <Col lg={6} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.organizationName}
                                        name="organizationName"
                                        readonly={true}
                                    />
                                </Col>
                                <Col xl={{span: 6, offset: 2,}} lg={{span: 8,}} md={{span: 12,}} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.contactName}
                                        name="contactName"
                                        readonly={true}
                                    />
                                </Col>
                                <Col xl={{span: 6, offset: 2,}} lg={{span: 8,}} md={{span: 12,}} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.contactPhone}
                                        name="contactPhone"
                                        readonly={true}
                                    />
                                </Col>
                            </Row>
                            <Row>
                                <Col lg={12} md={12} sm={24}>
                                    <ProFormText
                                        label={fieldLabels.address}
                                        name="address"
                                        readonly={true}
                                    />
                                </Col>
                            </Row>
                        </Card>
                        <Card title="资源信息" className={styles.card} bordered={false}>
                            <ProTable<HostComputerListItem, API.ListPagination>
                                //headerTitle="主机列表"
                                actionRef={actionRef}
                                rowKey="hostComputerId"
                                search={{
                                    // labelWidth: 90,
                                    // span: 7
                                }}
                                scroll={{x: true}}
                                toolBarRender={() => []}
                                pagination={{
                                    pageSize: 5, // 每页显示 10 条数据
                                }}
                                options={false}
                                request={hostComputerSelectList}
                                columns={columns}
                                rowSelection={{
                                    type: 'radio',
                                    onChange: (_, selectedRows) => {
                                        setSelectedRows(selectedRows);
                                        form.setFieldsValue({ resourceId: selectedRows[0]?.hostComputerId });
                                    },
                                }}
                            />
                        </Card>
                        <Card title="已选择主机" className={styles.card} bordered={false}
                            hidden={true}
                        >
                            <ProFormText
                                name="resourceId"
                                label="主机ID"
                                hidden={false}
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择主机',
                                    },
                                ]}
                                fieldProps={{
                                    value: selectedRowsState[0]?.hostComputerId,
                                }}
                            />
                        </Card>
                        {/*<Card title="账单信息" className={styles.card} bordered={false}>*/}
                        {/*    <Row gutter={16}>*/}
                        {/*        <Col lg={6} md={12} sm={24}>*/}
                        {/*            <ProFormRadio.Group*/}
                        {/*                name="billingCycle"*/}
                        {/*                label="计费周期"*/}
                        {/*                options={[*/}
                        {/*                    {*/}
                        {/*                        label: '每小时',*/}
                        {/*                        value: 'hour',*/}
                        {/*                    },*/}
                        {/*                    {*/}
                        {/*                        label: '每天',*/}
                        {/*                        value: 'day',*/}
                        {/*                    },*/}
                        {/*                    {*/}
                        {/*                        label: '每月',*/}
                        {/*                        value: 'month',*/}
                        {/*                    },*/}
                        {/*                ]}*/}
                        {/*            />*/}
                        {/*        </Col>*/}
                        {/*    </Row>*/}
                        {/*    <Row gutter={16}>*/}
                        {/*        <Col lg={6} md={12} sm={24}>*/}
                        {/*            <ProFormDigit*/}
                        {/*                label="单价"*/}
                        {/*                name="unitPriceNumber"*/}
                        {/*                rules={[*/}
                        {/*                    {*/}
                        {/*                        required: true,*/}
                        {/*                        message: '请输入单价',*/}
                        {/*                    },*/}
                        {/*                ]}*/}
                        {/*                width={200}*/}
                        {/*                fieldProps={{addonAfter: "元"}}*/}
                        {/*                placeholder="请输入单价"*/}
                        {/*            />*/}
                        {/*        </Col>*/}

                        {/*        <Col*/}
                        {/*            xl={{*/}
                        {/*                span: 6,*/}
                        {/*                offset: 2,*/}
                        {/*            }}*/}
                        {/*            lg={{*/}
                        {/*                span: 8,*/}
                        {/*            }}*/}
                        {/*            md={{*/}
                        {/*                span: 12,*/}
                        {/*            }}*/}
                        {/*            sm={24}*/}
                        {/*        >*/}
                        {/*            <ProFormDateTimePicker*/}
                        {/*                label="开始计费时间（可选）"*/}
                        {/*                width="md"*/}
                        {/*                name="start"*/}
                        {/*                placeholder={'开始日期'}*/}
                        {/*                // disabled={true}*/}
                        {/*            />*/}
                        {/*        </Col>*/}
                        {/*    </Row>*/}
                        {/*</Card>*/}
                    </PageContainer>
                </ProForm>
            )}
        </div>
    );
};
export default OrganizationOrderAddForm;
